﻿using System;
using System.Net.Sockets;
using System.IO;
using System.ComponentModel;

/* This class is used for managing player connections to the server
 * computer.  This holds information for reading/writing to the
 * socket stream to reduce the constant creation of streams.  In
 * addition, this class does the basic retrieving/writing to the
 * socket streams but does no parsing of the data.  It simply 
 * passes the return values to the server class
 */

namespace ThePushCSharp
{
    public class PlayerConnection
    {
        public Socket socket;
        public NetworkStream networkStream;
        public StreamReader streamReader;
        public StreamWriter streamWriter;

        //Creates a new connection with the new socket.
        //Sets up the read/write streams to the socket stream.
        public PlayerConnection(Socket socket)
        {
            this.socket = socket;
            networkStream = new NetworkStream(socket);
            streamWriter = new StreamWriter(networkStream);
            streamReader = new StreamReader(networkStream);
        }

        //Reads data from the socket stream.
        public String recv()
        {
            if (!socket.Connected)
                return "";

            return streamReader.ReadLine();
        }

        //Sends data to the socket stream - DOES NOT ENSURE CORRECTNESS!
        //Protocol: [messageType]   [sizeOfParameters]  [parameters]
        //          [1 byte]        [1 byte]            [0-255 bytes]
        public int send(char messageType, String parameters)
        {
            try
            {
                if (!socket.Connected)
                    return 0;

                streamWriter.WriteLine(messageType + parameters.Length + parameters);
                streamWriter.Flush();
            }
            catch
            {
                return -1;
            }

            return 1;
        }

        //Frees up the socket stream and related members
        public void close()
        {
            streamReader.Close();
            streamWriter.Close();
            networkStream.Close();
            socket.Close();
        }
    }
}
